import { BaseStorageService, PROJECT_CONFIG, StorageConfig } from './storage/baseStorageService';

// 收益计算记录数据接口
export interface SavedProfitCalculation {
  id: string;
  calculation_type: 'fund' | 'stock' | 'general';
  asset_code?: string;
  asset_name?: string;
  initial_investment: number;
  current_value: number;
  profit_loss: number;
  profit_rate: number;
  holding_days?: number;
  annualized_return?: number;
  calculation_data?: Record<string, any>; // 存储详细计算数据
  notes?: string;
  created_at: string;
  updated_at: string;
}

// 收益计算服务类 - 继承基础存储服务
class ProfitCalculationService extends BaseStorageService<SavedProfitCalculation> {
  constructor(config: StorageConfig = { 
    type: 'supabase',
    supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
    supabaseKey: import.meta.env.VITE_SUPABASE_ANON_KEY
  }) {
    // 使用项目统一配置中定义的收益计算存储名称
    super(PROJECT_CONFIG.STORE_NAMES.PROFIT_CALCULATIONS, config);
  }

  // 业务特定的方法 - 保存收益计算记录
  async saveProfitCalculation(calculation: SavedProfitCalculation): Promise<void> {
    // 验证用户登录状态
    const { isUserAuthenticated } = await import('../utils/userContext');
    if (!(await isUserAuthenticated())) {
      throw new Error('用户未登录，无法保存收益计算记录');
    }
    
    // 验证收益计算数据
    this.validateProfitCalculation(calculation);
    return this.save(calculation);
  }

  // 业务特定的方法 - 获取所有收益计算记录
  async getProfitCalculations(): Promise<SavedProfitCalculation[]> {
    return this.getAll();
  }

  // 业务特定的方法 - 根据ID获取收益计算记录
  async getProfitCalculationById(id: string): Promise<SavedProfitCalculation | null> {
    return this.getById(id);
  }

  // 业务特定的方法 - 删除收益计算记录
  async deleteProfitCalculation(id: string): Promise<void> {
    return this.delete(id);
  }

  // 业务特定的方法 - 批量删除收益计算记录
  async deleteProfitCalculations(ids: string[]): Promise<void> {
    return this.deleteMany(ids);
  }

  // 业务特定的方法 - 根据资产类型查询
  async getProfitCalculationsByType(calculationType: SavedProfitCalculation['calculation_type']): Promise<SavedProfitCalculation[]> {
    const allCalculations = await this.getProfitCalculations();
    return allCalculations.filter(calc => calc.calculation_type === calculationType);
  }

  // 业务特定的方法 - 根据资产代码查询
  async getProfitCalculationsByAssetCode(assetCode: string): Promise<SavedProfitCalculation[]> {
    const allCalculations = await this.getProfitCalculations();
    return allCalculations.filter(calc => calc.asset_code === assetCode);
  }

  // 业务特定的方法 - 获取收益统计信息
  async getProfitStatistics(): Promise<{
    totalCalculations: number;
    totalInitialInvestment: number;
    totalCurrentValue: number;
    totalProfitLoss: number;
    averageProfitRate: number;
    typeDistribution: Record<string, number>;
    profitableCount: number;
    lossCount: number;
  }> {
    const calculations = await this.getProfitCalculations();
    
    const totalInitialInvestment = calculations.reduce((sum, calc) => sum + calc.initial_investment, 0);
    const totalCurrentValue = calculations.reduce((sum, calc) => sum + calc.current_value, 0);
    const totalProfitLoss = calculations.reduce((sum, calc) => sum + calc.profit_loss, 0);
    const averageProfitRate = calculations.length > 0 
      ? calculations.reduce((sum, calc) => sum + calc.profit_rate, 0) / calculations.length 
      : 0;

    return {
      totalCalculations: calculations.length,
      totalInitialInvestment,
      totalCurrentValue,
      totalProfitLoss,
      averageProfitRate,
      typeDistribution: calculations.reduce((acc, calc) => {
        acc[calc.calculation_type] = (acc[calc.calculation_type] || 0) + 1;
        return acc;
      }, {} as Record<string, number>),
      profitableCount: calculations.filter(calc => calc.profit_loss > 0).length,
      lossCount: calculations.filter(calc => calc.profit_loss < 0).length
    };
  }

  // 验证收益计算记录的业务规则
  private validateProfitCalculation(calculation: SavedProfitCalculation): void {
    // 验证初始投资金额
    if (calculation.initial_investment <= 0) {
      throw new Error('初始投资金额必须大于0');
    }

    // 验证当前价值
    if (calculation.current_value < 0) {
      throw new Error('当前价值不能为负数');
    }

    // 验证计算类型
    const validTypes = ['fund', 'stock', 'general'];
    if (!validTypes.includes(calculation.calculation_type)) {
      throw new Error('无效的计算类型');
    }

    // 验证收益率计算
    const expectedProfitRate = ((calculation.current_value - calculation.initial_investment) / calculation.initial_investment) * 100;
    if (Math.abs(calculation.profit_rate - expectedProfitRate) > 0.01) {
      console.warn('收益率计算可能有误:', {
        expected: expectedProfitRate,
        actual: calculation.profit_rate
      });
    }

    // 验证盈亏金额计算
    const expectedProfitLoss = calculation.current_value - calculation.initial_investment;
    if (Math.abs(calculation.profit_loss - expectedProfitLoss) > 0.01) {
      console.warn('盈亏金额计算可能有误:', {
        expected: expectedProfitLoss,
        actual: calculation.profit_loss
      });
    }
  }

  // 计算年化收益率
  calculateAnnualizedReturn(profitRate: number, holdingDays: number): number {
    if (holdingDays <= 0) return 0;
    return (Math.pow(1 + profitRate / 100, 365 / holdingDays) - 1) * 100;
  }

  // 计算持有天数
  calculateHoldingDays(startDate: string, endDate?: string): number {
    const start = new Date(startDate);
    const end = endDate ? new Date(endDate) : new Date();
    return Math.floor((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
  }

  // 创建收益计算记录
  createProfitCalculation(data: {
    calculation_type: SavedProfitCalculation['calculation_type'];
    asset_code?: string;
    asset_name?: string;
    initial_investment: number;
    current_value: number;
    holding_days?: number;
    calculation_data?: Record<string, any>;
    notes?: string;
  }): SavedProfitCalculation {
    const now = new Date().toISOString();
    const profit_loss = data.current_value - data.initial_investment;
    const profit_rate = (profit_loss / data.initial_investment) * 100;
    const annualized_return = data.holding_days 
      ? this.calculateAnnualizedReturn(profit_rate, data.holding_days)
      : undefined;

    return {
      id: `profit_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      calculation_type: data.calculation_type,
      asset_code: data.asset_code,
      asset_name: data.asset_name,
      initial_investment: data.initial_investment,
      current_value: data.current_value,
      profit_loss,
      profit_rate,
      holding_days: data.holding_days,
      annualized_return,
      calculation_data: data.calculation_data,
      notes: data.notes,
      created_at: now,
      updated_at: now
    };
  }
}

// 创建默认服务实例 - 使用Supabase
export const profitCalculationService = new ProfitCalculationService();

// 导出服务类
export { ProfitCalculationService };